
let oldArrayPrototype = Array.prototype
let proto = Object.create(oldArrayPrototype)

Array.from(['push','pop','shift','unshift']).forEach(method=>{
    proto[method] = function(...args){
        oldArrayPrototype[method].call(this,...args)
        updateView()
        return oldArrayPrototype[method].call(this,...args)
    }
 
})

function observer(target){
    if(typeof target !== 'object' && target === null){
            return target 
    }
     
    if(Array.isArray(target)){
        target.__proto__ = proto
        return
    }

    for (let key in target){
        defineReactive(target,key,target[key])
    }

}

function defineReactive(target,key,value){ //数据劫持
    if(typeof value === 'object' && value !== null){
        observer(value)
    }
    Object.defineProperty(target,key,{
        get(){
            return value
        },

        set(newVal){
          if(newVal !== value){
            value = newVal
            updateView()
          }

        }
    })


}

function updateView(){
    console.log(`更新视图`);
}



let data = {
    name:'阿伟',
    age:18,
    like:['吃饭','睡觉']
}


observer(data.like)

// data.like[0] = '喝水' // 数组下标修改也会触发set
// data.like.push('coding')//push不触发set

// console.log(data.like);
data.sex= 'boy'
console.log(data);

